package com.nlp.visualization.controller.spring.controller;

import com.nlp.visualization.common.CONSTANTS;
import com.nlp.visualization.pojo.common.AjaxReturn;
import com.nlp.visualization.pojo.db.TManagerInfo;
import com.nlp.visualization.service.IJWTService;
import com.nlp.visualization.service.backEnd.IApiCountService;
import com.nlp.visualization.service.backEnd.IManagerInfoService;
import com.nlp.visualization.service.backEnd.IModelsService;
import com.nlp.visualization.service.backEnd.IUserSuggetionsService;
import com.nlp.visualization.utils.ComputerMonitorUtil;
import com.nlp.visualization.utils.MD5Util;
import com.nlp.visualization.utils.TimeHelper;
import com.nlp.visualization.utils.synUtils.SynParamUtil;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.enterprise.inject.Model;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @author LXM
 * @Title: NLPVisualizationTools
 * @Description:
 * @date 2018/5/11下午9:09
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    Logger logger = LoggerFactory.getLogger(AdminController.class);


    @Autowired
    private IManagerInfoService managerInfoService;

    @Autowired
    private IModelsService modelsService;

    @Autowired
    private IJWTService ijwtService;

    @Autowired
    private IUserSuggetionsService suggetionsService;

    @Autowired
    private IApiCountService apiCountService;


    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = {"application/json"})
    @ResponseBody
    public AjaxReturn doLogin(@RequestBody Map map) {

        //如果参数丢失
        if (map.size() < 2) {
            //返回参数丢失
            return new AjaxReturn(CONSTANTS.ERROR_PARAM_ERROR, "参数丢失");
        }
        String ID = (String) map.get("admin");
        String password = (String) map.get("password");
        //如果参数为空
        if (!SynParamUtil.checkParam(ID, password)) {
            //返回参数为空
            return new AjaxReturn(CONSTANTS.ERROR_PARAM_ERROR, "参数不能为空");
        }
        //开始登陆服务
        boolean res = managerInfoService.checkManagerInfo(ID, password);
        if (res) {
            //取出相关的用户信息
            Map filedMap = new HashedMap();
            filedMap.put("name", ID);
            TManagerInfo managerInfo = managerInfoService.findByField(filedMap);
            //30分钟过期令牌
            Map resMap = new HashedMap();
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.MINUTE, 30);
            Date date = c.getTime();
            String jwt = ijwtService.buildJwt(date);
            //生成Token
            resMap.put("access_token", jwt);
            resMap.put("name", managerInfo.getName());
            resMap.put("sex", managerInfo.getSex());
            resMap.put("description", managerInfo.getDescription());
            resMap.put("image", managerInfo.getImageUri());
            resMap.put("id", managerInfo.getId());
            resMap.put("time", managerInfo.getAddingTime());

            return new AjaxReturn(CONSTANTS.ERROR_SUCCESS, "成功", resMap);
        } else {
            return new AjaxReturn(CONSTANTS.ERROR_WRONG_PSW, "参数不能为空");
        }
    }


    @RequestMapping("/system/data")
    @ResponseBody
    public Map getSystemData() {

        Map map = new HashedMap();

        Map resMap = new HashedMap();
        int adminCount = managerInfoService.countAll();
        int modelCount = modelsService.count("模型");
        int dicCount = modelsService.count("词典");
        int sugCount = suggetionsService.countAll();
        resMap.put("admin", adminCount);
        resMap.put("dic", dicCount);
        resMap.put("model", modelCount);
        resMap.put("suggestion", sugCount);
        map.put("code", 0);
        map.put("data", resMap);
        return map;
    }

    /**
     * 接口的使用数据
     *
     * @return
     */
    @RequestMapping("/interface/data")
    @ResponseBody
    public Map getInterfaceDataToday() {

        Map map = new HashedMap();
        map.put("code", 0);
        map.put("data", apiCountService.countApiByToday());
        return map;
    }

    /**
     * 接口的使用数据
     *
     * @return
     */
    @RequestMapping("/interface/data/time")
    @ResponseBody
    public Map getInterfaceDataByTime() {

        Map map = new HashedMap();
        map.put("code", 0);
        map.put("day", apiCountService.countApiByToday());
        map.put("week", apiCountService.countApiByWeek());
        map.put("month", apiCountService.countApiByMonth());
        return map;
    }


    /**
     * 接口的使用数据的分布
     *
     * @return
     */
    @RequestMapping("/interface/totalData/time")
    @ResponseBody
    public Map getInterfaceData4Pie() {

        Map map = new HashedMap();
        map.put("code", 0);
        map.put("day", apiCountService.countEachApiTotalByToday());
        map.put("week", apiCountService.countEachApiTotalByWeek());
        map.put("month", apiCountService.countEachApiTotalByMonth());
        return map;
    }

    /**
     * 接口的使用数据的分布
     *
     * @return
     */
    @RequestMapping("/interface/totalData")
    @ResponseBody
    public Map getInterfacePerDataByTime() {

        Map map = new HashedMap();
        map.put("code", 0);
        map.put("data", apiCountService.countEachApiTotalByToday());
        return map;
    }

    @RequestMapping("/interface/all")
    @ResponseBody
    public Map getInterfaceAll() {

        Map map = new HashedMap();
        map.put("code", 0);
        map.put("data", apiCountService.interfaceAll());
        return map;
    }

    @RequestMapping("/interface/count")
    @ResponseBody
    public Map getInterfaceCountAll() {

        Map map = new HashedMap();
        map.put("code", 0);
        map.put("data", apiCountService.countAll());
        return map;
    }


    //    CPU内存等数据
    @RequestMapping("/system/info")
    @ResponseBody
    public Map getSystemInfo() {

        Map map = new HashedMap();
        map.put("cpu", ComputerMonitorUtil.getCpu());
        map.put("memory", ComputerMonitorUtil.getMemery());
        map.put("net", ComputerMonitorUtil.getNetInfo());
        return map;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.POST)
    @ResponseBody
    public AjaxReturn changeAdminInfomation(@RequestBody Map map, @PathVariable("id") int id) throws Exception {

        String name = (String) map.get("name");
        String sex = (String) map.get("sex");
        String imagepath = (String) map.get("image");
        String description = (String) map.get("description");
        String password = (String) map.get("password");
        TManagerInfo managerInfo = managerInfoService.findById(id);
        managerInfo.setDescription(description);
        managerInfo.setPassword(MD5Util.MD5(password));
        managerInfo.setImageUri(imagepath);
        managerInfo.setName(name);
        managerInfo.setSex(sex);
        managerInfoService.update(managerInfo);
        return new AjaxReturn(CONSTANTS.ERROR_SUCCESS, "修改成功");
    }


    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public AjaxReturn getAllAdminInfo() {

        return new AjaxReturn(CONSTANTS.ERROR_SUCCESS, "成功", managerInfoService.findAll());

    }


    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public AjaxReturn addNewAdmin(@RequestBody Map map) throws Exception {

        String name = (String) map.get("name");
        String sex = (String) map.get("sex");
        String imagepath = (String) map.get("image");
        String description = (String) map.get("description");
        String password = (String) map.get("password");
        password = MD5Util.MD5(password);
        TManagerInfo managerInfo = new TManagerInfo();
        managerInfo.setDescription(description);
        managerInfo.setPassword(MD5Util.MD5(password));
        managerInfo.setImageUri(imagepath);
        managerInfo.setName(name);
        managerInfo.setSex(sex);
        managerInfo.setAddingTime(TimeHelper.getTime().longValue() / 1000);
        managerInfoService.save(managerInfo);

        return new AjaxReturn(CONSTANTS.ERROR_SUCCESS, "成功");

    }


    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public AjaxReturn deleteAdmin(@PathVariable("id") int id) throws Exception {

        managerInfoService.deleteById(id);
        return new AjaxReturn(CONSTANTS.ERROR_SUCCESS, "成功");

    }


    @RequestMapping(value = "/models/bayes", method = RequestMethod.GET)
    @ResponseBody
    public AjaxReturn models() throws Exception {

        Map fieldMap = new HashedMap();
        fieldMap.put("name", "API BAYES");

        return new AjaxReturn(CONSTANTS.ERROR_SUCCESS, "成功", modelsService.findAllByField(fieldMap));

    }


    @RequestMapping(value = "/models/bayes", method = RequestMethod.DELETE)
    @ResponseBody
    public AjaxReturn DeleteBayesModels(HttpServletRequest request) throws Exception {

        int id = Integer.parseInt(request.getParameter("id"));
        modelsService.deleteById(id);
        return new AjaxReturn(CONSTANTS.ERROR_SUCCESS, "成功");

    }

}
